<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\WithdrawFund;
use App\Enums\WithdrawFundEnum;
use App\Helpers\ResponseHelper;
use App\Models\BalanceRecord;
use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;

class WithdrawFundController extends AdminController
{
    protected $status = [1 => '待审核', 2 => '审核通过', 3 => '审核失败'];

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WithdrawFund(['user']), function (Grid $grid) {
            $grid->model()->orderBy('status', 'asc')->orderBy('id', 'desc');
            $grid->column('id')->sortable();
            $grid->column('user.username');
            $grid->column('user.mobile');
            $grid->column('amount');
            $grid->column('actual_amount');
            $grid->column('status')->using($this->status)->label([
                1 => Admin::color()->gray(),
                2 => 'success',
                3 => 'danger',
            ]);;
            $grid->column('created_at');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('user.mobile')->width(3);
                $filter->equal('status')->select($this->status)->width(2);
            });
            $grid->disableCreateButton();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WithdrawFund(), function (Show $show) {
            $show->field('id');
            $show->field('user_id');
            $show->field('amount');
            $show->field('status');
            $show->field('fail_reason');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WithdrawFund(['user']), function (Form $form) {
            $form->text('user.username')->readOnly();
            $form->text('user.mobile')->readOnly();
            $form->decimal('amount')->readOnly();
            $form->decimal('actual_amount')->readOnly();
            if ($form->model()->status != 1) {
                $form->text('', '状态')->value(WithdrawFundEnum::getDescription($form->model()->status))->readOnly();
            } else {
                $form->radio('status')->options($this->status)->when(3, function (Form $form) {
                    $form->text('fail_reason');
                });
            }
        })->saving(function (Form $form) {
            $status = $form->input('status');
            $failReason = $form->input('fail_reason');
            $user = User::findOrFail($form->model()->user_id);

            if ($status == 3) {
                if ($failReason == '') {
                    return $form->response()->error('请填写失败原因');
                }
                try {
                    // 开始事务
                    DB::beginTransaction();

                    $user->balance += $form->model()->amount;
                    $user->save();
                    // 提交事务
                    DB::commit();
                } catch (\Exception $e) {
                    // 发生错误，回滚事务
                    DB::rollBack();

                    // 处理异常
                    return $form->response()->error($e->getMessage());
                }
            }
            if ($status == 2) {
                if (bcsub($user->balance, $form->model()->amount) < 0) {
                    return $form->response()->error('用户余额不足');
                }
                //创建余额记录
                try {
                    // 开始事务
                    DB::beginTransaction();

                    //创建余额记录
                    BalanceRecord::create([
                        'user_id' => $user->id,
                        'amount' => $form->model()->amount,
                        'type' => 2
                    ]);
                    // 提交事务
                    DB::commit();
                } catch (\Exception $e) {
                    // 发生错误，回滚事务
                    DB::rollBack();

                    // 处理异常
                    return $form->response()->error($e->getMessage());
                }
            }
        });
    }
}
